<?php
/**
 * 订单同步逻辑层
 */
namespace app\common\logic;

use app\common\logic\Base;
use mes\Mes;
use think\Db;
use app\common\model\Size as SizeModel;
use app\common\service\OrderMaterial as OrderMaterialService;

class Order extends Base
{

	/**
	 * 订单同步
	 *
	 * @author KING
	 * @date 2020年6月11日
	 *
	 * @param array $data	MES订单数据详细
	 * @param bool $printLog	打印日志
	 * @throws \Exception
	 */
	public function sync($data, $printLog=false) {
		$logName = 'syncOrder';
		$needDownloadPicSkuId = 0;	// 需要下载图片的产品skuid

		db()->startTrans();
		try {
			$clientOrdernum = arrayGet($data, 'produceOrderId'); // 客户订单号
			$clientOrderStatus = arrayGet($data, 'status'); // 客户订单号接单状态
			$stockType = arrayGet($data, 'stockType'); // 备货类型
			$sku = arrayGet($data, 'sku'); // 款号
			$mes = arrayGet($data, 'mes'); // 同步账号
			$history = arrayGet($data, 'history'); // 是否历史订单查询
			$logName .= $mes;
			if ($history) $logName .= 'History';

			if (empty($clientOrdernum) || empty($clientOrderStatus) || empty($sku)) throw new \Exception("数据解析异常");

			$msg = "客户订单号 {$clientOrdernum} 接口原始数据：".json_encode($data);
			if ($printLog) consoleLog($msg);
			addLog($msg, $logName);

			$orderInfo = db('order')->where('client_ordernum', $clientOrdernum)->where('status', '<>', 99)->find();
			$skuInfo = db('sku')->where('sku', $sku)->find();

			if ($orderInfo) {
				$msg = "客户订单号 {$clientOrdernum} 已存在";
				if ($printLog) consoleLog($msg);
				addLog($msg, $logName);
			}

			// 已作废的订单只更新订单状态，其它都不处理
            if($clientOrderStatus == '废除') $clientOrderStatus = '已作废';
			if($clientOrderStatus == '已作废') {
				if ($orderInfo) {
					$delOrderInfo = db('order')->where('client_ordernum', $clientOrdernum)->where('status', '=', 99)->find();
					if (!$delOrderInfo) {
                        db('order')->where('id', $orderInfo['id'])->update(['client_status' => 99, 'update_time' => time(),]);
                        $this->addOrderLog($orderInfo['id'], $orderInfo['client_ordernum'], "MES废除");
                    }
				}
                isset($orderInfo['client_status']) && $orderInfo['client_status'] == 99 && $orderInfo['client_status_del_time'] == 0 && db('order')->where('id', $orderInfo['id'])->update(['client_status_del_time' => time(),]);
                $msg = "客户订单号 {$clientOrdernum} 状态为 已作废，不作处理";
				if ($printLog) consoleLog($msg);
				addLog($msg, $logName);
				db()->commit();
				return;
			}

			if ($orderInfo) {
				$msg = "客户订单号 {$clientOrdernum} 产品SKU {$sku}已存在";
				if ($printLog) consoleLog($msg);
				addLog($msg, $logName);
			}

            if ((!isset($data['purchaseInfo']) || count($data['purchaseInfo']) == 0)
                && (!isset($data['pickMaterialInfo']) || count($data['pickMaterialInfo']) == 0)
            ) {
                $msg = "客户订单号 {$clientOrdernum} 物料与领料为空";
                addLog($msg, $logName);
                db()->commit();
                return true;
            }
			// 物料检测及入库start
			$purchaseList = $data['purchaseInfo'];
			$msg = "客户订单号 {$clientOrdernum} 待新增物料".count($purchaseList)."个";
			if ($printLog) consoleLog($msg);
			addLog($msg, $logName);
			$materialIds = $materialDosage = $materialLoss = $customerPrice = $weightMap = [];
			$aMaterialId = 0; // A面料ID
			foreach ($purchaseList as $sk => $sv) {
				$materialData = [
					'name' => $sv['materialName'],
					'type' => autoIdentifyType(arrayGet($sv, 'purchaseType', ''), $sv['materialName']),
					'material_sku' => $sv['materialSku'],
					'classify' => $sv['materialType'],			// 物料分类
					'customer_price' => $sv['price'],
					'supplier' => $sv['supplierName'],
					'model' => $sv['supplierCode'],
					'colornum' => $sv['supplierColorNum'],
					'color' => $sv['materialColor'],
					'contact' => $sv['supplierPhone'],
					'address' => $sv['supplierAddr'],
					'fabric_width' => $sv['width'],
					'weight' => $sv['weight'],
					'loss' => $sv['supplierLoss'],
					'unit' => '公斤',
					'use_time' => time(),
					'update_time' => time(),
				];
				if($sv['simpleUse'] > 0) $materialData['unit'] = '米';
				$materialInfo = db('material')->where('material_sku', $sv['materialSku'])->field('id,type')->find();
				if ($materialInfo) { // 存在则更新
					if ($materialInfo['type'] != '') unset($materialData['type']);	// 暂不更新物料类型，因有可能物料类型搞错导致其它款的物料类型也错
					$materialIds[] = $newMaterialId = $materialInfo['id'];
					db('material')->where('material_sku', $sv['materialSku'])->update($materialData);
				} else { // 不存在则新增
					$materialData['create_time'] = time();
					$materialData['is_auto_import'] = $mes;
					$materialIds[] = $newMaterialId = db('material')->insertGetId($materialData);
				}
				if(isset($materialDosage[$newMaterialId])) {
					$materialDosage[$newMaterialId] += $sv['simpleUse'] > 0 ? $sv['simpleUse'] : $sv['singleAmountKg'];
				} else {
					$materialDosage[$newMaterialId] = $sv['simpleUse'] > 0 ? $sv['simpleUse'] : $sv['singleAmountKg'];
				}
				$materialLoss[$newMaterialId] = $sv['supplierLoss'];
				$customerPrice[$newMaterialId] = $sv['price'];
				$weightMap[$newMaterialId] = $sv['weight']; // 客户克重

				if (arrayGet($sv, 'purchaseType', '') == '面料A') {
					$aMaterialId = $newMaterialId;
				}
			}
			if ($materialIds) {
				$msg = "客户订单号 {$clientOrdernum} 新增物料ID集:".implode(',', $materialIds);
				if ($printLog) consoleLog($msg);
				addLog($msg, $logName);
			}
			// 物料检测及入库end


			// 领料检测及入库start
			$pickMaterialIds = []; // 领料ID集
			$pickPurchaseList = $data['pickMaterialInfo'];
			$msg = "客户订单号 {$clientOrdernum} 待新增领料".count($pickPurchaseList)."个";
			if ($printLog) consoleLog($msg);
			addLog($msg, $logName);
			foreach ($pickPurchaseList as $keyP => $valP) {
				foreach ($valP['detailList'] as $sk => $sv) {
					$materialData = [
						'name' => $sv['materialName'],
						'material_sku' => $sv['materialSku'],
						'color' => $sv['materialColor'],
						'fabric_width' => $sv['width'],
						'weight' => round($sv['weight'], 2),
						'unit' => $sv['unitName'],
						'is_pick' => 1,
						'use_time' => time(),
						'update_time' => time(),
					];
					$materialInfo = db('material')->where('material_sku', $sv['materialSku'])->field('id')->find();
					if ($materialInfo) { // 存在则更新
						$pickMaterialIds[] = $newMaterialId = $materialInfo['id'];
						db('material')->where('material_sku', $sv['materialSku'])->update($materialData);
					} else { // 不存在则新增
						$materialData['type'] = autoIdentifyType(arrayGet($sv, 'pickMaterialTypeStr', ''), $sv['materialName']);
						$materialData['create_time'] = time();
						$materialData['is_auto_import'] = $mes;
						$pickMaterialIds[] = $newMaterialId = db('material')->insertGetId($materialData);
					}

					if(!isset($weightMap[$newMaterialId])) $weightMap[$newMaterialId] = $materialData['weight'];
				}
			}
			if ($pickMaterialIds) {
				$msg = "客户订单号 {$clientOrdernum} 新增领料ID集:".implode(',', $pickMaterialIds);
				if ($printLog) consoleLog($msg);
				addLog($msg, $logName);
			}
			// 领料检测及入库end


			// 合并物料和领料（订单需要关联的材料）
			$materialIds = array_merge($materialIds, $pickMaterialIds);


			// 更新物料及用量信息start
			if ($orderInfo) {
				// 更新产品用量及订单用量
				foreach ($materialDosage as $mk => $mv) {
					$upData = [
						'customer_dosage' => $mv,
						'loss' => arrayGet($materialLoss, $mk, 0),
						'customer_price' => arrayGet($customerPrice, $mk, 0),
						'update_time' => time()
					];
					db('sku_material')->where(['sku_id' => arrayGet($skuInfo, 'id', 0), 'material_id' => $mk])->update($upData);

					if (isset($weightMap[$mk])) $upData['weight'] = $weightMap[$mk];
					db('order_material')->where(['order_id' => arrayGet($orderInfo, 'id', 0), 'material_id' => $mk])->update($upData);
				}
			}
			// 更新物料及用量信息end


			// 尺码信息检测及入库start
			$sizeArr = array_map("strtoupper", array_column($data['orderInfo'], 'sizeName'));
			$psSize = [];
			foreach ($data['orderInfo'] as $s) {
				if (!db('size')->where('name', strtoupper($s['sizeName']))->field('id')->find()) {
					(new SizeModel())->save(['name' => strtoupper($s['sizeName'])]);
				}
				$psSize[] = ['100'=>0];	// 初始化用，无特殊意义
			}
			// 尺码信息检测及入库end

			$orderExt = [
                'pic' => $data['pic'],
				'cost_profit' => $data['processCostFee'],
				'cost' => $data['processCostFee']-$data['processProfit'],
				'cost_scale' => $data['scale'],
				'design_code' => $data['designCode'],
				'mes_factory' => $data['producer'],
				'client_ordernum' => $data['produceOrderId'],
				'update_time' => time(),
			]; // 订单扩展信息


			// SKU检测及入库start
			$skuData = [
				'sku' => $sku,
				'ps_size_name' => json_encode($sizeArr),	// 尺码名称集
				'ps_part' => json_encode(['100' => '其它']),
				'ps_size' => json_encode($psSize),
				'cost_profit' => $data['processCostFee'],		// 加工费（含利润）
				'cost' => $data['processCostFee']-$data['processProfit'],		// 加工费（不含利润）
				'profit' => $data['processProfit'],		// 加工费利润
				'cost_scale' => $data['scale'],		// 加工费倍率
				'update_time' => time(),
			];
			if($skuData['cost']<12){
                $skuData['fabrics_process_complexity']=0; //面辅工艺难度
            }elseif($skuData['cost']>=12 && $skuData['cost']<=20){
                $skuData['fabrics_process_complexity']=1;
            }else{
                $skuData['fabrics_process_complexity']=2;
            }
			if (!$skuInfo) $skuData['sku_type'] = $data['weavingType'];
			if (isset($data['secondProcess'][0])) {
				$skuData['special_process_a_name'] = $data['secondProcess'][0]['processName'];
				$skuData['special_process_a_count'] = $data['secondProcess'][0]['simpleUse'];
				$skuData['special_process_a_unitprice'] = $data['secondProcess'][0]['unitPrice'];
				$skuData['special_process_a_price'] = $skuData['special_process_a_count'] * $skuData['special_process_a_unitprice'];
				if ($skuInfo && $skuInfo['special_process_a_level']==0 || !$skuInfo) $skuData['special_process_a_level'] = 3;

				$orderExt['special_process_a_name'] = $data['secondProcess'][0]['processName'];
				$orderExt['special_process_a_supplier'] = $data['secondProcess'][0]['supplierName'];
				$orderExt['special_process_a_count'] = $data['secondProcess'][0]['simpleUse'];
				$orderExt['special_process_a_unitprice'] = $data['secondProcess'][0]['unitPrice'];
				$orderExt['special_process_a_price'] = $skuData['special_process_a_count'] * $skuData['special_process_a_unitprice'];
				$orderExt['special_process_a_level'] = 3;
			}
			if (isset($data['secondProcess'][1])) {
				$skuData['special_process_b_name'] = $data['secondProcess'][1]['processName'];
				$skuData['special_process_b_count'] = $data['secondProcess'][1]['simpleUse'];
				$skuData['special_process_b_unitprice'] = $data['secondProcess'][1]['unitPrice'];
				$skuData['special_process_b_price'] = $skuData['special_process_b_count'] * $skuData['special_process_b_unitprice'];
				if ($skuInfo && $skuInfo['special_process_b_level']==0 || !$skuInfo) $skuData['special_process_b_level'] = 3;

				$orderExt['special_process_b_name'] = $data['secondProcess'][1]['processName'];
				$orderExt['special_process_b_supplier'] = $data['secondProcess'][1]['supplierName'];
				$orderExt['special_process_b_count'] = $data['secondProcess'][1]['simpleUse'];
				$orderExt['special_process_b_unitprice'] = $data['secondProcess'][1]['unitPrice'];
				$orderExt['special_process_b_price'] = $skuData['special_process_b_count'] * $skuData['special_process_b_unitprice'];
				$orderExt['special_process_b_level'] = 3;
			}
			if (isset($data['secondProcess'][2])) {
				$skuData['zj_name'] = $data['secondProcess'][2]['processName'];
				$skuData['zj_count'] = $data['secondProcess'][2]['simpleUse'];
				$skuData['zj_unitprice'] = $data['secondProcess'][2]['unitPrice'];
				$skuData['zj_price'] = $skuData['zj_count'] * $skuData['zj_unitprice'];
				if ($skuInfo && $skuInfo['zj_level']==0 || !$skuInfo) $skuData['zj_level'] = 3;

				$orderExt['special_process_c_name'] = $data['secondProcess'][2]['processName'];
				$orderExt['special_process_c_supplier'] = $data['secondProcess'][2]['supplierName'];
				$orderExt['special_process_c_count'] = $data['secondProcess'][2]['simpleUse'];
				$orderExt['special_process_c_unitprice'] = $data['secondProcess'][2]['unitPrice'];
				$orderExt['special_process_c_price'] = $orderExt['special_process_c_count'] * $orderExt['special_process_c_unitprice'];
				$orderExt['special_process_c_level'] = 3;
			}
			if (isset($data['secondProcess'][3])) {
				$orderExt['special_process_d_name'] = $data['secondProcess'][3]['processName'];
				$orderExt['special_process_d_supplier'] = $data['secondProcess'][3]['supplierName'];
				$orderExt['special_process_d_count'] = $data['secondProcess'][3]['simpleUse'];
				$orderExt['special_process_d_unitprice'] = $data['secondProcess'][3]['unitPrice'];
				$orderExt['special_process_d_price'] = $orderExt['special_process_d_count'] * $orderExt['special_process_d_unitprice'];
				$orderExt['special_process_d_level'] = 3;
			}
			if (isset($data['secondProcess'][4])) {
				$orderExt['special_process_e_name'] = $data['secondProcess'][4]['processName'];
				$orderExt['special_process_e_supplier'] = $data['secondProcess'][4]['supplierName'];
				$orderExt['special_process_e_count'] = $data['secondProcess'][4]['simpleUse'];
				$orderExt['special_process_e_unitprice'] = $data['secondProcess'][4]['unitPrice'];
				$orderExt['special_process_e_price'] = $orderExt['special_process_e_count'] * $orderExt['special_process_e_unitprice'];
				$orderExt['special_process_e_level'] = 3;
			}

			$price = 0;
			$skuData['purchasing_profit_price'] = 0;
			$skuData['purchasing_price'] = 0;
			$skuData['purchasing_profit'] = 0;
			$skuData['fabirc_process_price'] = 0;
			$skuData['clothes_process_price'] = 0;
			$skuData['pick_price'] = 0;
			$skuData['consume_price'] = 0;
			$skuData['other_price'] = 0;
			$skuData['cost_little'] = 0;

			$caichuangPosition = 0;	// 默认非定位裁剪
			$clothCostFeeDetailList = []; // 工厂采购物料
			foreach ($data['clothCostFeeDetail'] as $ck => $cv) {
				if ($cv['category'] == '工厂采购物料' || $cv['category'] == '物料费') {
					$clothCostFeeDetailList = $cv['clothCostFeeDetail'];
					$sumCostDesc = explode('<br>', $cv['sumCostDesc']);
					$skuData['purchasing_profit_price'] = round(arrayGet($sumCostDesc, 0, 1), 2);
					$skuData['purchasing_price'] = round($cv['littleSumCost'],2);
					$skuData['purchasing_profit'] = $skuData['purchasing_profit_price'] - $skuData['purchasing_price'];

					$orderExt['material_cost_total'] = round($cv['sumCostTotal'],2);
					$orderExt['material_cost_little'] = round($cv['littleSumCost'],2);
				} elseif($cv['category'] == '面辅料二次工艺') {
					$skuData['fabirc_process_price'] = round($cv['littleSumCost'],2);

					$orderExt['process_cost_total'] = round($cv['sumCostTotal'],2);
					$orderExt['process_cost_little'] = round($cv['littleSumCost'],2);
				} elseif($cv['category'] == '成衣二次工艺') {
					if ($cv['clothCostFeeDetail']) {
						$allTitle = implode(';', array_column($cv['clothCostFeeDetail'], 'title'));
						if (mb_strpos($allTitle, '定位裁剪') !== false) $caichuangPosition = 1;
                        $orderExt['dress_process_names'] = $allTitle;
                        $orderExt['dress_process_counts']=implode('/', array_column($cv['clothCostFeeDetail'], 'simpleUse'));
                        $orderExt['dress_process_unitprices']=implode('/', array_column($cv['clothCostFeeDetail'], 'unitPrice'));
                        $orderExt['dress_process_prices']=implode('/', array_column($cv['clothCostFeeDetail'], 'price'));
					}
					$skuData['clothes_process_price'] = round($cv['littleSumCost'], 2);
					$orderExt['dress_cost_total'] = round($cv['sumCostTotal'],2);
					$orderExt['dress_cost_little'] = round($cv['littleSumCost'],2);
				} elseif($cv['category'] == 'SHEIN发放物料') {
					$skuData['pick_price'] = round($cv['littleSumCost'], 2);
				} elseif($cv['category'] == '耗材费用') {
					$skuData['consume_price'] = round($cv['sumCostTotal'], 2);
				} elseif($cv['category'] == '其他费用') {
					$skuData['other_price'] = round($cv['littleSumCost'], 2);
				} elseif($cv['category'] == '加工费') {
					$skuData['cost_little'] = round($cv['littleSumCost'], 2);

					$orderExt['cost_little'] = round($cv['littleSumCost'],2);
				}

				if (array_key_exists('sumCostTotal', $cv)) {
					$price += $cv['sumCostTotal'];
				} else {
					$price += arrayGet($cv, 'littleSumCost');
				}
                if ($cv['category'] == '加工费') {
                    $orderExt['cost_jiagong_littleSumCost'] = round($cv['littleSumCost'] ?? 0, 2);
                    $orderExt['cost_jiagong_scale'] = round($cv['scale'] ?? 0, 2);
                    $orderExt['cost_jiagong_sumCostForSale'] = round($cv['sumCostForSale'] ?? 0, 2);
                }
                $orderExt['dress_changkuan_unitPrice'] = 0;
                if (count($cv['clothCostFeeDetail']) > 0) {
                    foreach ($cv['clothCostFeeDetail'] as $kd100 => $vd100) {
                        if (isset($vd100['title'])) {
                            $temp0 = strpos($vd100['title'], '长款');
                            $temp1 = strpos($vd100['title'], '补贴');
                            is_int($temp0)
                            && is_int($temp1)
                            && $orderExt['dress_changkuan_unitPrice'] = round($vd100['unitPrice'] ?? 0, 2);
                        }
                    }
                }

			}
			$orderExt['price'] = isset($data['orderPrice']) ? $data['orderPrice'] : $price; // orderPrice订单单件价格（如mes有核价，则为核价后的价格,可能也会增加耗材费$price会缺失这块）
			$skuData['price'] = $price;	// 售价
			$skuData['style_name'] = getStyleName($sku);	// 识别款式名称
			if (!$skuInfo || $skuInfo && $skuInfo['a_material_id'] == 0) $skuData['a_material_id'] = $aMaterialId;	// 面料A的物料ID

			if ($skuInfo) {
				$skuId = $skuInfo['id'];
				$msg = "客户订单号 {$clientOrdernum} sku（{$sku}）已存在";
				if ($printLog) consoleLog($msg);
				addLog($msg, $logName);

				// 图片检测，有更新则重新下载替换
				if (stripos($data['pic'], 'url=') !== false) {
					$picTmp = explode('url=', $data['pic']);
					$mesPic = $picTmp[1];
				} else $mesPic = $data['pic'];

				// 需要更新图片
                $needUpdatePic = $this->_needUpdatePic($skuInfo['ori_pic'], $mesPic,$skuInfo);
				if ($needUpdatePic >= 1) $skuData['ori_pic'] = $mesPic;
                if ($needUpdatePic == 2) {
                    $skuData['ori_pic'] = $mesPic;
                    $skuData['pic_download_flag'] = 0;
                    $needDownloadPicSkuId = $skuId;
                }

				db('sku')->where('id', $skuId)->update($skuData);

				$caichuangPosition = $skuInfo['caichuang_position'];
			} else {
				$msg = "客户订单号 {$clientOrdernum} sku（{$sku}）不存在";
				if ($printLog) consoleLog($msg);
				addLog($msg, $logName);

				$skuData['caichuang_position'] = $caichuangPosition;	// 裁剪方式（0正常裁剪，1定位裁剪，2对格对条裁剪）

				if (stripos($data['pic'], 'url=') !== false) {
					$picTmp = explode('url=', $data['pic']);
					$mesPic = $picTmp[1];
				} else $mesPic = $data['pic'];
				$skuData['pic'] = $mesPic;
				$skuData['ori_pic'] = $mesPic;
				$skuData['is_auto_import'] = $mes;
				$skuData['create_time'] = time();
				$skuData['update_time'] = time();
				$needDownloadPicSkuId = $skuId = db('sku')->insertGetId($skuData);
			}
			$msg = "客户订单号 {$clientOrdernum} sku_id:{$skuId}";
			if ($printLog) consoleLog($msg);
			addLog($msg, $logName);
			// SKU检测及入库end

			// 订单检测及入库start
			$oType = 'FOB';
			if ($data['orderType'] == 'FOB') $oType = 'FOB';
			elseif ($data['orderType'] == 'CMT') $oType = 'CMT';
			elseif ($data['orderType'] == '新CMT') $oType = 'CMT2';
			$type = 'normal';
			if ($data['isFirst'] == '首单' || $data['isFirst'] == '首' || $data['isFirst'] == '新') $type = 'new';
			elseif ($data['isUrgent'] == '紧急' || $data['isUrgent'] == '急') $type = 'emergent';
			$orderData = [
				'quantity' => $data['quantity'],
				'shipment_time' => strtotime($data['deliveryTime'] . ' 00:00:00'),
				'update_time' => time(),
			];
			if (isset($data['orderPrice'])) {
				$orderData['order_price'] = $data['orderPrice'];	// 订单单件价格（如mes有核价，则为核价后的价格）
			}

			// 记录客户订单状态
			$clientStatus = array_search($clientOrderStatus, config('mimo.client_status'));
			$orderData['client_status'] = $clientStatus===false?100:$clientStatus;
            $orderData['client_status_txt'] = $clientOrderStatus;
			if ($clientStatus === false) {
				$msg = "客户订单号 {$clientOrdernum} 客户订单状态异常：" . $clientOrderStatus;
				if ($printLog) consoleLog($msg);
				addLog($msg, $logName);
			}

			if ($orderInfo) {
				$orderId = $orderInfo['id'];
				if ($orderInfo['shipment_time'] != strtotime($data['deliveryTime'] . ' 00:00:00') || $orderInfo['quantity'] != $data['quantity']) {
					db('order')->where('id', $orderId)->update($orderData);
					$msg = "客户订单号{$clientOrdernum} 更新成功";
					if ($printLog) consoleLog($msg);
					addLog($msg, $logName);
				}
			} else {
				$orderData['client_ordernum'] = $clientOrdernum;
				$orderData['sku'] = $data['sku'];
				$orderData['type'] = $type;
				$orderData['o_type'] = $oType;
				$orderData['is_auto_import'] = $mes;
				$orderData['factory_id'] = 0;
				$orderData['caichuang_position'] = $caichuangPosition;
				$orderData['is_auto_import'] = $mes;
				if($skuInfo){ //返单自动分配工厂
                    $where = [
                        ['sku', '=', $skuInfo['sku']],
                        ['factory_id', '>', 0],
                    ];
                    //$orderFactoryInfo = db('order')->where($where)->findOrEmpty();
                    //if ($orderFactoryInfo) $orderData['factory_id'] = $orderFactoryInfo['factory_id'];
                }
				$orderData['is_new'] = $skuInfo ? 0 : 1;
				$orderData['outgo_price'] = arrayGet($skuInfo, 'outsource_price', 0);
				$orderData['stock_type'] = array_search($stockType, config('mimo.stock_type')) === false ? 0 : array_search($stockType, config('mimo.stock_type'));
				$orderData['accept_time'] = strtotime($data['acceptOrderTime']);
				$orderData['create_time'] = strtotime($data['placeOrderTime']);
				//返单第一次标识
                $this->my_return_first($orderData);
                $clientOrdernumOrderInfo = db('order')->where('client_ordernum', $clientOrdernum)->where('status', '<>', 99)->find();
                if($clientOrdernumOrderInfo){ //已存在该订单
                    db()->rollback(); //回滚
                    addLog("客户订单号 {$clientOrdernum} 重复插入， 执行回滚", $logName);
                    return true;
                }
				$orderId = db('order')->insertGetId($orderData);

				// 记录为进行中
				$redis = getRedis();
				$redis->hSet(ORDER_ING, $clientOrdernum, $orderData['create_time']);

				$msg = "客户订单号 {$clientOrdernum} 创建成功";
				if ($printLog) consoleLog($msg);
				addLog($msg, $logName);
			}
			// 订单检测及入库end


			// 订单扩展信息检测及入库start
			$orderExtInfo = db('order_ext')->where('order_id', $orderId)->find();
			if ($orderExtInfo) {
				if ($orderExtInfo['special_process_a_level'] > 0) unset($orderExtInfo['special_process_a_level']);
				if ($orderExtInfo['special_process_b_level'] > 0) unset($orderExtInfo['special_process_b_level']);
				if ($orderExtInfo['special_process_c_level'] > 0) unset($orderExtInfo['special_process_c_level']);
				if ($orderExtInfo['special_process_d_level'] > 0) unset($orderExtInfo['special_process_d_level']);
				if ($orderExtInfo['special_process_e_level'] > 0) unset($orderExtInfo['special_process_e_level']);
                $orderExt['update_time'] = time();
				db('order_ext')->where('order_id', $orderId)->update($orderExt);
				$msg = "客户订单号 {$clientOrdernum} 订单扩展信息更新成功";
			} else {
				$orderExt['order_id'] = $orderId;
                $orderExt['ori_pic'] =  $orderExt['pic'];
				$orderExt['create_time'] = time();
				db('order_ext')->insertGetId($orderExt);
				$msg = "客户订单号 {$clientOrdernum} 订单扩展信息入库成功";
			}
			if ($printLog) consoleLog($msg);
			addLog($msg, $logName);
			// 订单扩展信息检测及入库end


			// 删除SKU之前已关联的物料start
			$skuMaterialIdsOri = db('sku_material')->where('sku_id', $skuId)->column('material_id');
			if ($skuMaterialIdsOri) {
				$skuMaterialIdsDelete = array_diff($skuMaterialIdsOri, $materialIds);
				if ($skuMaterialIdsDelete) {
					$map = [
						['sku_id', '=', $skuId],
						['material_id', 'in', $skuMaterialIdsDelete],
					];
					db('sku_material')->where($map)->delete();
					$msg = "客户订单号 {$clientOrdernum} 产品SKU删除原有材料关联".implode(',', $skuMaterialIdsDelete);
					if ($printLog) consoleLog($msg);
					addLog($msg, $logName);
				}
			}
			// 删除SKU之前已关联的物料end

			// 删除订单物料表中已关联的记录start
			$materialIdsOri = db('order_material')->where(['order_id'=>$orderId])->column('material_id');
			if ($materialIdsOri) {
				$orderMaterialIdsDelete = array_diff($materialIdsOri, $materialIds);
				if ($orderMaterialIdsDelete) {
					$map = [
						['order_id', '=', $orderId],
						['material_id', 'in', $orderMaterialIdsDelete],
					];
					db('order_material')->where($map)->delete();
					$msg = "客户订单号 {$clientOrdernum} 订单物料表删除原有材料关联".implode(',', $orderMaterialIdsDelete);
					if ($printLog) consoleLog($msg);
					addLog($msg, $logName);
				}
			}
			// 删除订单物料表中已关联的记录end


			// 订单关联物料start
			$omIds = [];
			$orderMaterialService = new OrderMaterialService();
			foreach ($materialIds as $materialId) {
				$orderMaterialInfo = db('order_material')->where(['order_id'=>$orderId, 'material_id' => $materialId])->field('mid')->find();
				if (!$orderMaterialInfo) {
					$materialDosageAvg = 0; // 米莫用量
					if ($skuInfo) { // 返单
						// 1、返单优化使用精准用量start
						$materialDosageAvg = db('sku_material')->where(['sku_id' => $skuInfo['id'], 'material_id' => $materialId])->value('accurate_dosage', 0);
						// 2、返单优化使用精准用量start

						// 2、返单计算历史5次裁床实际单件用量平均值start
						if ($materialDosageAvg == 0) {
							$orderHistory = db('order o')
                                ->join('order_material om', "o.id=om.order_id and om.caichuang_shiji_dosage>0 and om.material_id={$materialId}")
                                ->where('sku', $sku)->where('id', '<', $orderId)->order('id desc')->limit(5)->column('id');
							if(count($orderHistory)>=5){ //存在历史5次裁床实际单件用量 去大去小取平均，
                                $map = [
                                    ['material_id', '=', $materialId],
                                    ['order_id', 'in', $orderHistory],
                                    ['caichuang_shiji_dosage', '>', 0]
                                ];
                                $materialDosageArr = db('order_material')->where($map)->column('caichuang_shiji_dosage');
                                if (count($materialDosageArr) >= 3) {
                                    // 去除最大最小值后取平均值
                                    $materialDosageAvg = round((array_sum($materialDosageArr)-max($materialDosageArr)-min($materialDosageArr))/(count($materialDosageArr)-2), 2);
                                } elseif(count($materialDosageArr) > 0) {
                                    $materialDosageAvgTmp = round(array_sum($materialDosageArr)/count($materialDosageArr), 2);
                                    if ($materialDosageAvgTmp > 0) $materialDosageAvg = $materialDosageAvgTmp;
                                }
                            }
						}
						// 2、返单计算历史5次裁床实际单件用量平均值end

						if ($materialDosageAvg == 0) $materialDosageAvg = arrayGet($materialDosage, $materialId, 0);
					} else { // 首单取客户用量
						$materialDosageAvg = arrayGet($materialDosage, $materialId, 0);
					}

					// 检测是否需要验布缩水 及 物料进度列表是否显示
					$needCheckclothShrinkData = $orderMaterialService->checkNeedCheckclothShrink($orderId, $materialId);
					$needCheckcloth = arrayGet($needCheckclothShrinkData, 'need_checkcloth', 0);
					$needShrink = arrayGet($needCheckclothShrinkData, 'need_shrink', 0);
					$caigouShow = arrayGet($needCheckclothShrinkData, 'caigou_show', 1);

					$materialInfo = db('material')->find($materialId);
					$orderMaterial = [
						'order_id' => $orderId,
						'client_ordernum' => $clientOrdernum,
						'material_id' => $materialId,
						'caigou_unitprice' => $materialInfo['customer_price'], // 采购单价 目前直接使用  客户单价
						'customer_price' => $materialInfo['customer_price'], // 客户单价
						'customer_dosage' => arrayGet($materialDosage, $materialId, 0), // 用量 目前直接使用 客户用量
						'fabric_width' => $materialInfo['fabric_width'],
                        'fabric_width_once' => $materialInfo['fabric_width'],
						'weight' => $materialInfo['weight'],
                        'weight_once' => $materialInfo['weight'],
						'material_dosage' => $materialDosageAvg, // 米莫用量（首单取客户用量，返单优先取精准用量，没有精准用量再取最近5次裁床用量均值）
						'loss' => arrayGet($materialLoss, $materialId, 0),
						'need_checkcloth' => $needCheckcloth !=2 ? $needCheckcloth : 0,
						'need_shrink' => $needShrink !=2 ? $needShrink : 0,
						'caigou_show' => $caigouShow,	// 是否在采购进度显示
						'create_time' => time(),
						'update_time' => time(),
					];
					db('order_material')->insertGetId($orderMaterial);
					$omIds[] = $materialId;
				}
			}
			if ($omIds) {
				$msg = "客户订单号 {$clientOrdernum} 新增关联物料ID（".implode(',', $omIds)."）";
				if ($printLog) consoleLog($msg);
				addLog($msg, $logName);
			}
			// 订单关联物料end


			// 订单关联尺码start
			$osIds = [];
			foreach ($data['orderInfo'] as $sizeInfo) {
				$osInfo = db('order_size')->where('order_id', $orderId)->where('size_name', strtoupper($sizeInfo['sizeName']))->find();
				if ($osInfo) {
					$orderSize = [
						'order_id' => $orderId,
						'client_ordernum' => $clientOrdernum,
						'size_name' => strtoupper($sizeInfo['sizeName']),
						'order_count' => $sizeInfo['quantity'],
						'update_time' => time(),
					];
					db('order_size')->where('mid', $osInfo['mid'])->update($orderSize);
					$osIds[] = $osInfo['mid'];
				} else {
					$orderSize = [
						'order_id' => $orderId,
						'client_ordernum' => $clientOrdernum,
						'size_name' => strtoupper($sizeInfo['sizeName']),
						'order_count' => $sizeInfo['quantity'],
						'create_time' => time(),
						'update_time' => time(),
					];
					$osIds[] = db('order_size')->insertGetId($orderSize);
				}
			}
			$msg = "客户订单号 {$clientOrdernum} 订单关联尺码".count($data['orderInfo'])."个";
			if ($printLog) consoleLog($msg);
			addLog($msg, $logName);
			// 订单关联尺码end


			// 物料关联sku、物料使用日志记录start
			$skuMaterialIds = [];
			foreach ($materialIds as $materialId) {
				$skuMaterialInfo = db('sku_material')->where(["sku_id" => $skuId, "material_id" => $materialId])->field('mid')->find();
				if (!$skuMaterialInfo) {
					$skuMaterialData = [
						'sku_id' => $skuId,
						'material_id' => $materialId,
						'create_time' => time(),
						'update_time' => time(),
					];
					// MES客户用量
					$skuMaterialData['customer_dosage'] = arrayGet($materialDosage, $materialId, 0);
					$skuMaterialData['material_dosage'] = arrayGet($materialDosage, $materialId, 0);
					$skuMaterialData['loss'] = arrayGet($materialLoss, $materialId, 0);
					$skuMaterialIds[] = db('sku_material')->insertGetId($skuMaterialData);
				} else {
					$skuMaterialData = [
						'customer_dosage' => arrayGet($materialDosage, $materialId, 0),
						'loss' => arrayGet($materialLoss, $materialId, 0),
					];
					db('sku_material')->where('mid', $skuMaterialInfo['mid'])->update($skuMaterialData);
				}

				// 物料使用日志记录
				$materialLogInfo = db('material_log')->where(["order_id" => $orderId, "material_id" => $materialId])->field('id')->find();
				if (!$materialLogInfo) {
					$materialLog = [
						'material_id' => $materialId,
						'order_id' => $orderId,
						'client_ordernum' => $clientOrdernum,
						'sku_id' => $skuId,
						'sku' => $sku,
						'create_time' => time(),
						'update_time' => time(),
					];
					db('material_log')->insertGetId($materialLog);
				}
			}

			if (!$skuMaterialIds) {
				$msg = "客户订单号 {$clientOrdernum} sku关联".count($skuMaterialIds)."个物料成功";
				if ($printLog) consoleLog($msg);
				addLog($msg, $logName);
			}
			// 物料关联sku、物料使用日志记录start


			// 客户物料单件成本处理start
			foreach ($clothCostFeeDetailList as $cck => $ccv) {
				$titleArr = explode('/', $ccv['title']);
				$materialSku = end($titleArr);
				$materialInfo = db('material')->where("material_sku", $materialSku)->field('id')->find();
				if ($materialInfo) {
					$msg = "客户订单号 {$clientOrdernum} 更新客户物料单件成本（material_id:{$materialInfo['id']},material_sku:{$materialSku},custom_simple_cost:{$ccv['materialMeter']}）";
					if ($printLog) consoleLog($msg);
					addLog($msg, $logName);
					db('order_material')->where(['order_id'=>$orderId, 'material_id'=>$materialInfo['id']])->update(["custom_simple_cost" => $ccv['materialMeter']]);
				}
			}
			// 客户物料单件成本处理end


			// 尾货处理start
			if ($stockType == '尾货' && !$orderInfo) {
				$factoryId = db('order')->where('sku', $sku)->order('id desc')->value('factory_id');
				$factoryId = intval($factoryId);

				$orderData = [
					'factory_id' => $factoryId,
					'caigou_status' => 1,
					'caigou_cost_status' => 1,
					'cost_audit_status' => 1,
					'caichuang_can_do' => 1,
					'caichuang_status' => 1,
					'chejian_status' => 1,
					'caigou_over_time' => time(),
					'cost_audit_time' => time(),
					'caichuang_can_do_time' => time(),
					'caichuang_over_time' => time(),
					'chejian_over_time' => time(),
					'update_time' => time(),
					'remark' => '尾货',
				];
				db('order')->where('id', $orderId)->update($orderData);

				$omData = [
					'caigou_confirm_status' => 1,
					'caigou_status' => 1,
					'caigou_cost_status' => 1,
					'caichuang_status' => 1,
					'caigou_confirm_time' => time(),
					'caigou_over_time' => time(),
					'caigou_cost_over_time' => time(),
					'caichuang_over_time' => time(),
					'update_time' => time(),
				];
				db('order_material')->where('order_id', $orderId)->update($omData);

				db('order_size')->where("order_id", $orderId)->update(['shicai_count'=>Db::raw('order_count'), 'jiaohuo_count'=>Db::raw('order_count')]);

				$osList = db('order_size')->where("order_id", $orderId)->select();
				foreach ($osList as $k => $v) {
					$insData = [
						'factory_id' => $factoryId,
						'order_id' => $orderId,
						'client_ordernum' => arrayGet($orderInfo, 'client_ordernum', ''),
						'zhahao' => ($k+1),
						'jianshu' => $v['order_count'],
						'size_name' => $v['size_name'],
						'chuanghao' => 88888888,
						'chejian_start_time' => time(),
						'tail_start_time' => time(),
						'create_time' => time(),
						'update_time' => time(),
					];
					db('order_user')->insertGetId($insData);
				}

				$msg = "客户订单号 {$clientOrdernum} 尾货处理成功";
				if ($printLog) consoleLog($msg);
				addLog($msg, $logName);
			}
			// 尾货处理end

			db()->commit();

			if ($needDownloadPicSkuId) {
				queue('app\common\job\DownloadPic', $needDownloadPicSkuId, rand(0, 10), 'DownloadPic');
			}
		} catch (\Exception $e) {
			db()->rollback();
			if ($printLog) consoleLog($e->getFile(). ' Line:' . $e->getLine());
			throw new \Exception("订单{$clientOrdernum} ".$e->getMessage());
		}
	}

    /**
     * 单个订单同步处理
     * @param int $order_id
     * @param string $client_ordernum
     * @author zhuguosen 905502314@qq.com
     * @date 2022/4/20
     */
    public function sync_one($order_id = 0, $client_ordernum = '')
    {
        $where = [];
        if ($order_id > 0) {
            $where[] = ['o.id', '=', $order_id];
        }
        if ($client_ordernum != '') {
            $where[] = ['o.client_ordernum', '=', $client_ordernum];
        }
        $info = db('order o')
            ->field('o.id, o.client_ordernum ,o.sku ,o.is_auto_import
            ')
            ->where($where)->find();
        if (!isset($info['id'])) {
            return false;
        }
        $mesLib = new Mes();
        $mes = intval($info['is_auto_import']);
        $config = [
            'private_key' => env("mes{$mes}.private_key"),
            'app_id' => env("mes{$mes}.app_id"),
            'app_secure' => env("mes{$mes}.app_secure"),
            'host' => env("mes{$mes}.host"),
        ];
        $mesLib->setConfig($config);
        $result = $mesLib->getProduceOrderInfo($info['client_ordernum']);
        addLog($result, 'sync_one_sam');
        $result = json_decode($result, true);
        if ($result['msg'] != 'success') {
            return false;
        }
        return $this->sync_getProduceOrderInfo($result['info']);
    }

    private function sync_getProduceOrderInfo($info)
    {
        $logName = 'syncOrder_getProduceOrderInfo';
        $clientOrderStatus = $info['status'];
        $clientOrdernum = $info['produceOrderId'];
        $orderInfo = db('order')->where('client_ordernum', $info['produceOrderId'])->where('status', '<>', 99)->find();
        db()->startTrans();
        try {
            switch (1) {//订单状态修改
                case 1:
                    // 已作废的订单只更新订单状态，其它都不处理
                    if ($clientOrderStatus == '废除') $clientOrderStatus = '已作废';
                    if ($clientOrderStatus == '已作废') {
                        if ($orderInfo) {
                            $delOrderInfo = db('order')->where('client_ordernum', $orderInfo['client_ordernum'])->where('status', '=', 99)->find();
                            if (!$delOrderInfo) {
                                db('order')->where('id', $orderInfo['id'])->update(['client_status' => 99, 'update_time' => time(),]);
                                $this->addOrderLog($orderInfo['id'], $orderInfo['client_ordernum'], "MES废除");
                            }
                        }
                        isset($orderInfo['client_status']) && $orderInfo['client_status'] == 99 && $orderInfo['client_status_del_time'] == 0 && db('order')->where('id', $orderInfo['id'])->update(['client_status_del_time' => time(),]);
                        $msg = "客户订单号 {$orderInfo['client_ordernum']} 状态为 已作废，不作处理";
                        addLog($msg, $logName);
                        db()->commit();
                        return true;
                    }
                    // 记录客户订单状态
                    $clientStatus = array_search($clientOrderStatus, config('mimo.client_status'));
                    $orderData['client_status'] = $clientStatus === false ? 100 : $clientStatus;
                    $orderData['client_status_txt'] = $clientOrderStatus;
                    if ($clientStatus === false) {
                        $msg = "客户订单号 {$clientOrdernum} 客户订单状态异常：" . $clientOrderStatus;
                        addLog($msg, $logName);
                    }
                    db('order')->where('client_ordernum', $orderInfo['client_ordernum'])
                        ->update([
                            'client_status_sync_time' => time(),
                            'client_status_sync' => 0,
                            'client_status' => $orderData['client_status'],
                            'client_status_txt' => $info['status'],
                        ]);

                    //货期时间修改
                    $orderData = [
                        'quantity' => $info['quantity'],
                        'shipment_time' => strtotime($info['deliveryTime'] . ' 00:00:00'),
                        'update_time' => time(),
                    ];
                    if ($orderInfo['shipment_time'] != strtotime($info['deliveryTime'] . ' 00:00:00') || $orderInfo['quantity'] != $info['quantity']) {
                        db('order')->where('client_ordernum', $orderInfo['client_ordernum'])->update($orderData);
                    }
                    db()->commit();
                    return true;
                    break;
            }
        } catch (\Exception $e) {
            db()->rollback();
            throw new \Exception("订单{$orderInfo['client_ordernum']} " . $e->getMessage());
        }
    }

    /**
     * 要同is_auto_import
     * @param array $order_id
     * @param array $client_ordernum
     * @return bool|void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @author zhuguosen 905502314@qq.com
     * @date 2022/4/20
     */
    public function sync_many($order_id = [], $client_ordernum = [])
    {
        $where = [];
        if ($order_id != []) {
            $where[] = ['o.order_id', 'in', $order_id];
        }
        if ($client_ordernum != []) {
            $where[] = ['o.client_ordernum', 'in', $client_ordernum];
        }
        $list = db('order o')
            ->field('o.id, o.id as order_id ,o.client_ordernum ,o.sku ,o.is_auto_import
            ')
            ->where($where)->select();
        if (count($list) <= 0) {
            return false;
        }
        $is_auto_import = 1;//1=小辉辉,2=名贵坊,3=十义
        $client_ordernum_array = [];
        foreach ($list as $k => $v) {
            $client_ordernum_array[] = $v['client_ordernum'];
            $is_auto_import = $v['is_auto_import'];
        }
        $client_ordernum_str = implode(',', $client_ordernum_array);
        $mesLib = new Mes();
        $mes = intval($is_auto_import);
        $config = [
            'private_key' => env("mes{$mes}.private_key"),
            'app_id' => env("mes{$mes}.app_id"),
            'app_secure' => env("mes{$mes}.app_secure"),
            'host' => env("mes{$mes}.host"),
        ];
        $mesLib->setConfig($config);
        $result = $mesLib->getOrderInfo($client_ordernum_str);
        addLog($result, 'sync_many_sam');
//        $result = '{"code":0,"info":{"acceptOrderTime":"2022-04-07 18:46:17","clothCostFeeDetail":[{"category":"加工费","clothCostFeeDetail":[{"burningPrintTipFlag":false,"materialMeter":"-","price":"0.37","profitRate":0.0970,"simpleAccount":"-","simpleUse":"-","supplierLoss":"-","supplierProfit":"-","title":"运腰带","unitPrice":"0.37"},{"burningPrintTipFlag":false,"materialMeter":"-","price":"0.12","profitRate":0.0970,"simpleAccount":"-","simpleUse":"-","supplierLoss":"-","supplierProfit":"-","title":"反腰带","unitPrice":"0.12"},{"burningPrintTipFlag":false,"materialMeter":"-","price":"0.15","profitRate":0.0970,"simpleAccount":"-","simpleUse":"-","supplierLoss":"-","supplierProfit":"-","title":"落腰带于衫身","unitPrice":"0.15"},{"burningPrintTipFlag":false,"materialMeter":"-","price":"0.14","profitRate":0.0970,"simpleAccount":"-","simpleUse":"-","supplierLoss":"-","supplierProfit":"-","title":"四线合肩缝","unitPrice":"0.14"},{"burningPrintTipFlag":false,"materialMeter":"-","price":"0.27","profitRate":0.0970,"simpleAccount":"-","simpleUse":"-","supplierLoss":"-","supplierProfit":"-","title":"四线上平袖","unitPrice":"0.27"},{"burningPrintTipFlag":false,"materialMeter":"-","price":"0.30","profitRate":0.0970,"simpleAccount":"-","simpleUse":"-","supplierLoss":"-","supplierProfit":"-","title":"四线埋夹","unitPrice":"0.30"},{"burningPrintTipFlag":false,"materialMeter":"-","price":"0.22","profitRate":0.0970,"simpleAccount":"-","simpleUse":"-","supplierLoss":"-","supplierProfit":"-","title":"冚袖口*2","unitPrice":"0.22"},{"burningPrintTipFlag":false,"materialMeter":"-","price":"0.25","profitRate":0.0970,"simpleAccount":"-","simpleUse":"-","supplierLoss":"-","supplierProfit":"-","title":"冚下摆*1","unitPrice":"0.25"},{"burningPrintTipFlag":false,"materialMeter":"-","price":"0.08","profitRate":0.0970,"simpleAccount":"-","simpleUse":"-","supplierLoss":"-","supplierProfit":"-","title":"驳领","unitPrice":"0.08"},{"burningPrintTipFlag":false,"materialMeter":"-","price":"0.18","profitRate":0.0970,"simpleAccount":"-","simpleUse":"-","supplierLoss":"-","supplierProfit":"-","title":"四线上领","unitPrice":"0.18"},{"burningPrintTipFlag":false,"materialMeter":"-","price":"0.15","profitRate":0.0970,"simpleAccount":"-","simpleUse":"-","supplierLoss":"-","supplierProfit":"-","title":"拉剪后领捆条或织带","unitPrice":"0.15"},{"burningPrintTipFlag":false,"materialMeter":"-","price":"0.19","profitRate":0.0970,"simpleAccount":"-","simpleUse":"-","supplierLoss":"-","supplierProfit":"-","title":"间后领内捆线","unitPrice":"0.19"},{"burningPrintTipFlag":false,"materialMeter":"-","price":"0.08","profitRate":0.0970,"simpleAccount":"-","simpleUse":"-","supplierLoss":"-","supplierProfit":"-","title":"车主唛*1(吊唛)","unitPrice":"0.08"},{"burningPrintTipFlag":false,"materialMeter":"-","price":"0.07","profitRate":0.0970,"simpleAccount":"-","simpleUse":"-","supplierLoss":"-","supplierProfit":"-","title":"车洗水唛*1","unitPrice":"0.07"}],"littleSumCost":"2.57","scale":2.40,"sumCostDesc":"6.77<br>(含倍率：6.17,含利润：0.60)","sumCostForSale":"6.17","sumCostTotal":"6.77"},{"category":"物料费","clothCostFeeDetail":[{"burningPrintTipFlag":false,"invoiceState":2,"materialMeter":"7.88","price":"7.88","profitRate":0.0970,"simpleAccount":"1.07","simpleUse":"1.18","superTaxRate":"0","superTaxRateDecimal":0.0000,"supplierLoss":"10%","supplierProfit":"-","title":"T002#牛奶丝间条T002#/16MLZS0326-766","unitPrice":"6.69"},{"burningPrintTipFlag":false,"invoiceState":2,"materialMeter":"0.01","price":"0.01","profitRate":0.0970,"simpleAccount":"0.30","simpleUse":"0.32","superTaxRate":"0","superTaxRateDecimal":0.0000,"supplierLoss":"8%","supplierProfit":"-","title":"5MM透明定型条/F00003658","unitPrice":"0.02"}],"littleSumCost":"7.88","sumCostDesc":"8.65<br>(含利润：0.76)","sumCostTotal":"8.65"},{"category":"面辅料二次工艺","clothCostFeeDetail":[],"littleSumCost":"0","sumCostDesc":"0","sumCostTotal":"0"},{"category":"成衣二次工艺","clothCostFeeDetail":[],"littleSumCost":"0","sumCostDesc":"0","sumCostTotal":"0"}],"cutBedInfo":[{"quantityInterval":"104","sizeName":"0XL"},{"quantityInterval":"202","sizeName":"1XL"},{"quantityInterval":"306","sizeName":"2XL"},{"quantityInterval":"102","sizeName":"3XL"},{"quantityInterval":"32","sizeName":"4XL"}],"cutBedQty":746,"deliveryTime":"2022-04-18","designCode":"W1102542112023079","isFirst":"","isUrgent":"普通","orderInfo":[{"quantity":130,"sizeName":"0XL"},{"quantity":210,"sizeName":"1XL"},{"quantity":290,"sizeName":"2XL"},{"quantity":90,"sizeName":"3XL"},{"quantity":30,"sizeName":"4XL"}],"orderPrice":"15.63","orderType":"FOB","pic":"https://img.ltwebstatic.com/images3_pi/2022/01/20/16426441310c1570a1d0f1173d850efde6628d98dc.jpg","placeOrderTime":"2022-04-07 18:09:18","processCostFee":6.7662960000,"processProfit":0.5982960000,"produceOrderId":8606000,"producer":"分厂-板桥九厂","quantity":750,"refSku":"","scale":2.40,"secondProcess":[],"sku":"sf2112025356457804","status":"已发货","stockType":"JIT","weavingType":"针织"},"msg":"success"}';
        $result = json_decode($result, true);
        if ($result['msg'] != 'success') {
            return false;
        }
        return $this->sync_getOrderInfo($result['info']);
    }

    /**
     *
     * @author  huanghuixiang
     * @date 2022/10/21 16:37
     */
    public function _syncOrderStatus(){
        set_time_limit(0);
        ini_set('memory_limit', '512M');
        error_reporting(E_ALL & ~E_NOTICE);

        $mesLib = new Mes();
        $mes = 2;
        $config = [
            'private_key' => env("mes{$mes}.private_key"),
            'app_id' => env("mes{$mes}.app_id"),
            'app_secure' => env("mes{$mes}.app_secure"),
            'host' => env("mes{$mes}.host"),
        ];
        $mesLib->setConfig($config);
        // $redis = getRedis();
        $result = [];
        $sql='SELECT  is_auto_import,client_ordernum,`status`,client_status,FROM_UNIXTIME(create_time,"%Y-%m-%d") as add_time  from  wx_order where `status` in(0,1) and client_status !=99 
         and is_auto_import=1  ';
        $sql2 = $sql.' GROUP BY  add_time  ORDER BY   add_time asc';
        $list=Db::query($sql2);
        foreach ($list as $key=>$value){
            $result = $mesLib->queryProduceOrderInfoV2($value['add_time'].' 00:00:00',$value['add_time'].' 23:59:59' );
            $data = json_decode($result, true);
            //addLog(count($data['info']),  'CountQueryProduceOrderInfoV2');
            if(!empty($data['info'])){
                foreach ($data['info'] as  $key2=>$value2){
                    $clientOrderStatus=$value2['status'];
                    // 记录客户订单状态
                    $clientStatus = array_search($clientOrderStatus, config('mimo.client_status'));
                    $orderData['client_status'] = $clientStatus===false?1000:$clientStatus;
                    $orderData['client_status_txt'] = $clientOrderStatus;
                    $orderData['update_time'] = time();
                    $orderData['client_status_sync'] = 0;
                    $orderData['client_status_sync_time'] = time();
                    if ($clientStatus === false) {
                        $msg = "客户订单号 {$value2['produceOrderId']} 客户订单状态异常：" . $clientOrderStatus;
                    }
                    db('order')->where('client_ordernum', $value2['produceOrderId'])->update($orderData);
                    //addLog($value2['produceOrderId'], 'InsertQueryProduceOrderInfo');
                }
            }

        }
        echo 'done';
        exit;
    }
	/**
	 * 图片是否需更新
	 *
	 * @author King
	 * @date 2021年11月19日
	 *
	 * @param string $oriPic			旧图片
	 * @param string $mesPic			mes新图片
     *
     * @return integer 0不需要更新，1只需要更新ori_pic，2需要重新下载并更新pic/ori_pic
	 */
	public function _needUpdatePic($oriPic, $mesPic,$skuInfo) {
		if (empty($mesPic) || $oriPic == $mesPic) return 0;
        //占位图地址
        if ($mesPic == 'https://doc.020mes.com/doc_020mes/2022/03/04/16463651693636538893.png') {
            return 0;
        }
        if ($skuInfo['pic_download_flag'] == 1) {
            return 0;
        }
        if (parse_url($mesPic, PHP_URL_QUERY) == null) {
            if (trim($skuInfo['pic']) != '') {//下载的文件存在就不用重新下载
                $temp = parse_url($skuInfo['pic']);
                if (file_exists(env('root_path') . 'public/' . $temp['path']) == true) {
                    return 1;
                }
            }
            return 2;
        }

        // 获取旧图片过期时间
        $oriExpireTime = 0;
        $queryString = parse_url($oriPic, PHP_URL_QUERY);
        if($queryString) {
            parse_str($queryString, $dataOri);
            if (isset($dataOri['Expires'])) $oriExpireTime = $dataOri['Expires'];
        }

        // 获取mes图片过期时间
        $newExpireTime = 0;
        $queryString = parse_url($mesPic, PHP_URL_QUERY);
        if($queryString) {
            parse_str($queryString, $dataNew);
            if (isset($dataNew['Expires'])) $newExpireTime = $dataNew['Expires'];
        }

		$oriBaseName = '';
		if(!empty($oriPic)) $oriBaseName = pathinfo($oriPic, PATHINFO_FILENAME);
		$mesBaseName = pathinfo($mesPic, PATHINFO_FILENAME);
		if ($oriBaseName == $mesBaseName) { // 文件名相同
            if ($oriExpireTime == $newExpireTime) return 0; // 过期时间一样，不更新
            else return 1; // 只需要更新ori_pic，不需要重新下载
        } else {
            if ($newExpireTime == 0 || $newExpireTime > 0 && $newExpireTime > time()) {
                return 2;   // 需要重新下载
            } elseif ($newExpireTime > 0 && $newExpireTime < time()) {
                return 1; // 只需要更新ori_pic，不需要重新下载
            } else return 0;
        }

	}

    /**
     * 添加订单日志
     *
     * @author KING
     * @date 2020年7月25日
     *
     * @param integer $orderId			订单ID
     * @param string $clientOrdernum	订单号
     * @param string $remark			备注
     * @return boolean
     */
    /**
     * 添加订单日志v2  与 app\mp\admin\Admin=> addOrderLog() 方法相似
     * @param $orderId
     * @param $clientOrdernum
     * @param $remark
     * @param array $ext
     * @return bool
     * @author zhuguosen 905502314@qq.com
     * @date 2022/3/17
     */
    public function addOrderLog($orderId, $clientOrdernum, $remark, $ext = [], $type = [])
    {
        if ($type == []) {
            if (empty($orderId) && empty($clientOrdernum)) return false;
            if (empty($orderId)) {
                $orderId = db('order')->where('client_ordernum', $clientOrdernum)->order('id desc')->value('id', 0);
            } elseif (empty($clientOrdernum)) {
                $clientOrdernum = db('order')->where('id', $orderId)->value('client_ordernum', '');
            }
        }
        $logData = [
            'type' => $type['type'] ?? 0,
            'uid' => $ext['ADMIN_ID'] ?? 0,
            'order_id' => $orderId,
            'client_ordernum' => $clientOrdernum,
            'order_material_id' => $type['order_material_id'] ?? 0,
            'url' => $ext['url'] ?? '',
            'module' => $ext['module'] ?? '',
            'controller' => $ext['controller'] ?? '',
            'action' => $ext['action'] ?? '',
            'param' => $ext['param'] ?? '',
            'remark' => $remark,
            'ip' => $ext['ip'] ?? '',
            'create_time' => time(),
        ];
        db('order_log')->insert($logData);
        return true;
    }

    /**
     * 返单第一次标识 order.type_ext=my_return_first
     * 查检这订单是否应该标识为 返单第一次
     * mes 的type= 紧急程度(normal普通，new新单，emergent紧急单)
     * 当mes过来的订单为new新单时，+24小时后的第1个同sku的订单 就为返单第一次
     * @author zhuguosen 905502314@qq.com
     * @date 2022/6/8
     *
     *  新增：第一次做
     *  第一次做定义为：type=normal，并且该sku之前没做过
     *  @author huanghuixiang
     */
    public function my_return_first(&$orderData)
    {
        $orderData['type_ext'] = '';
        //start
        // 是否第一次做
        $first_count = db('order')->field('id')->where([
            'sku' => $orderData['sku']
        ])->count();
        if ($first_count <=0 && $orderData['type']=="normal"){
            $orderData['type_ext'] = 'my_first';
            return true;
        }
        // end
        $my_return_first_info = db('order')->field('id')->where([
            'sku' => $orderData['sku'],
            'type_ext' => 'my_return_first',
        ])->find();
        if (isset($my_return_first_info['id'])) {
            return false;
        }
        $new_info = db('order')->field('id,create_time')->where([
            'sku' => $orderData['sku'],
            'type' => 'new',
        ])->order('id desc')->find();
        if (!isset($new_info['id'])) {
            return false;
        }
        if (($new_info['create_time'] + 24 * 3600) <= time()) {
            $orderData['type_ext'] = 'my_return_first';
            return true;
        }
        return false;
    }
}